package com.ym.wcp.framework.utils;

import com.ym.wcp.framework.exception.BizException;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

public class ValidatorUtil {

    private static final Validator validator;

    static {
        validator = Validation
                .byProvider(HibernateValidator.class)
                .configure()
                .failFast(true)
                .buildValidatorFactory().getValidator();
    }

    private static <T> void start(T t) {
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(t);
        if (constraintViolations.size() > 0) {
            StringBuilder validateError = new StringBuilder();
            for (ConstraintViolation<T> constraintViolation : constraintViolations) {
                validateError.append(constraintViolation.getMessage()).append(";");
            }
            throw new BizException(validateError.toString());
        }
    }

    public static <T> void validate(T t) {
        if (t == null) {
            throw new BizException("验证对象不能为空");
        }
        start(t);
    }

    public static <T> void validates(T... t) {
        if (t == null) {
            throw new BizException("验证对象不能为空");
        }
        for (T e : t) {
            start(e);
        }
    }
}
